package com.puboot.module.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.puboot.common.util.CoreConst;
import com.puboot.common.util.Pagination;
import com.puboot.exception.ArticleNotFoundException;
import com.puboot.module.admin.model.*;
import com.puboot.module.admin.service.*;
import com.puboot.module.admin.vo.ArticleConditionVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

import static com.puboot.common.util.CoreConst.THEME_PREFIX;

/**
 * CMS页面相关接口
 *
 * @author Linzhaoguan
 * @version V1.0
 * @date 2019年9月11日
 */
@Controller
@AllArgsConstructor
public class BlogWebController {

    private final BizArticleService bizArticleService;
    private final BizCategoryService categoryService;
    private final BizThemeService bizThemeService;
    private final BizTagsService bizTagsService;
    private final BizAboutUsService bizAboutUsService;
    private final BizRotationService bizRotationService;

    /**
     * 首页
     *
     * @param model
     * @param vo
     * @return
     */
    @GetMapping({"/", "/blog/index/{pageNumber}"})
    public String index(@PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                        ArticleConditionVo vo,
                        Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/index.html";
        }
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        } else {
            List<BizRotationImg> rotationImgs = bizRotationService.getImageByStatus(CoreConst.STATUS_VALID);
            model.addAttribute("rotationImgs", rotationImgs);//轮播文章
        }
        model.addAttribute("pageUrl", "blog/index");
        model.addAttribute("categoryId", "index");
        //获取轮播图文章
        List<BizArticle> rotationArticles = bizArticleService.getRotationArticlesDescUpdatetime();
        model.addAttribute("rotationArticles", rotationArticles);

        //获取置顶文章
        List<BizArticle> topArticles = bizArticleService.getTopArticlesDescUpdatetime();

        model.addAttribute("topArticles", topArticles);

        //loadMainPage(model, vo);
        // 先去掉替换模板功能，写死一个模板
        // return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/index";
    }

    /**
     * 分类列表
     *
     * @param categoryId
     * @param pageNumber
     * @param model
     * @return
     */
    @GetMapping({"/blog/category/{categoryId}", "/blog/category/{categoryId}/{tagId}", "/blog/category/{categoryId}/{tagId}/{pageNumber}"})
    public String category(@PathVariable("categoryId") Integer categoryId,
                           @PathVariable(value = "tagId", required = false) Integer tagId,
                           @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                           Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/category/" + (pageNumber == null ? categoryId : categoryId + "/" + pageNumber) + ".html";
        }
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setCategoryId(categoryId);
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        }

        if (tagId != null && tagId != 0) {
            vo.setTagId(tagId);
            model.addAttribute("pageUrl", "/blog/category/" + categoryId + "/" + tagId);
        } else {
            model.addAttribute("pageUrl", "/blog/category/" + categoryId + "/" + 0);
        }

        model.addAttribute("categoryId", categoryId);

        List<BizTags> bizTags = bizTagsService.findByCategoryId(categoryId);
        model.addAttribute("bizTags", bizTags);
        model.addAttribute("tagId", tagId);

        loadMainPage(model, vo);
        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/news";
    }

    /**
     * 文章详情
     *
     * @param model
     * @param articleId
     * @return
     */
    @GetMapping("/blog/article/{articleId}")
    public String article(Model model, @PathVariable("articleId") Integer articleId) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/article/" + articleId + ".html";
        }
        BizArticle article = bizArticleService.selectById(articleId);
        if (article == null || CoreConst.STATUS_INVALID.equals(article.getStatus())) {
            throw new ArticleNotFoundException();
        }
        model.addAttribute("article", article);
        model.addAttribute("categoryId", article.getCategoryId());

        BizCategory bizCategory = categoryService.selectById(article.getCategoryId());
        model.addAttribute("categoryName", bizCategory.getName());

        //推荐文章最多5个

        List<BizArticle> bizArticles = bizArticleService.getTop5RecommendedDesc();
        model.addAttribute("bizArticles", bizArticles);

        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/article";
        return THEME_PREFIX + "cweb" + "/news_view";
    }

    /**
     * 关于我们
     *
     * @param model
     * @return
     */
    @GetMapping({"/blog/aboutus"})
    public String aboutUs(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/aboutus/index.html";
        }

        //获取关于我们
        BizAboutUs aboutUs = bizAboutUsService.getAboutUs();
        model.addAttribute("aboutUs", aboutUs);

        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/about_us";
    }


    /**
     * 联系我们
     *
     * @param model
     * @return
     */
    @GetMapping({"/blog/contactus"})
    public String contactUs(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/contactus/index.html";
        }
        //获取关于我们
        BizAboutUs aboutUs = bizAboutUsService.getAboutUs();
        model.addAttribute("aboutUs", aboutUs);
        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/contact_us";
    }

    /**
     * 计算器
     *
     * @param model
     * @return
     */
    @GetMapping({"/blog/calculator"})
    public String calculator(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/calculator/index.html";
        }

        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/calculator";
    }

    /**
     * 计算器
     *
     * @param model
     * @return
     */
    @GetMapping({"/blog/calculator/one"})
    public String calculatorOne(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/calculator/one.html";
        }

        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/calculator_one";
    }

    /**
     * 计算器
     *
     * @param model
     * @return
     */
    @GetMapping({"/blog/calculator/two"})
    public String calculatorTwo(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/calculator/two.html";
        }

        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/calculator_two";
    }

    /**
     * 计算器
     *
     * @param model
     * @return
     */
    @GetMapping({"/blog/calculator/three"})
    public String calculatorThree(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/calculator/three.html";
        }

        //return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
        return THEME_PREFIX + "cweb" + "/calculator_three";
    }


    /**
     * 标签列表
     *
     * @param tagId
     * @param model
     * @return
     */
    @GetMapping({"/blog/tag/{tagId}", "/blog/tag/{tagId}/{pageNumber}"})
    public String tag(@PathVariable("tagId") Integer tagId,
                      @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                      Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/index/tag/" + (pageNumber == null ? tagId : tagId + "/" + pageNumber) + ".html";
        }
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setTagId(tagId);
        if (pageNumber != null) {
            vo.setPageNumber(pageNumber);
        }
        model.addAttribute("pageUrl", "blog/tag/" + tagId);
        //loadMainPage(model, vo);
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
    }


    /**
     * 评论
     *
     * @param model
     * @return
     */
    @GetMapping("/blog/comment")
    public String comment(Model model) {
        if (CoreConst.SITE_STATIC.get()) {
            return "forward:/html/comment/comment.html";
        }
        model.addAttribute("categoryId", "comment");
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/comment";
    }

    private void loadMainPage(Model model, ArticleConditionVo vo) {
        vo.setStatus(CoreConst.STATUS_VALID);
        IPage<BizArticle> page = new Pagination<>(vo.getPageNumber(), vo.getPageSize());
        List<BizArticle> articleList = bizArticleService.findByCondition(page, vo);


        List<Long> items = new ArrayList<>();

        long currentPage = page.getCurrent();

        long totalPages = page.getPages();

        if (totalPages <= 3) {
            for (long i = 1; i <= totalPages; i++) {
                items.add(i);
            }
        } else if (currentPage == 1) {
            for (long i = 1; i <= 3; i++) {
                items.add(i);
            }
        } else if (currentPage < totalPages) {
            for (long i = currentPage - 1; i <= currentPage + 1; i++) {
                items.add(i);
            }
        } else {
            for (long i = totalPages - 2; i <= totalPages; i++) {
                items.add(i);
            }
        }


        model.addAttribute("items", items);
        model.addAttribute("page", page);
        model.addAttribute("articleList", articleList);//文章列表
        if (vo.getCategoryId() != null) {
            BizCategory category = categoryService.getById(vo.getCategoryId());
            if (category != null) {
                model.addAttribute("categoryName", category.getName());
            }
        }
    }

    @GetMapping("/blog/card/{type}")
    public String card(@PathVariable("type") String type) {
        return THEME_PREFIX + "cweb" + "/card_" + type;
    }

    @GetMapping({"/blog/eg"})
    public String eg() {
        return THEME_PREFIX + "cweb" + "/electricity_generation";
    }

    @GetMapping({"/blog/magnesiumsmelting"})
    public String magnesiumsmelting() {
        return THEME_PREFIX + "cweb" + "/magnesium_smelting";
    }

    @GetMapping({"/blog/powergrid"})
    public String powergrid() {
        return THEME_PREFIX + "cweb" + "/powergrid";
    }

    @GetMapping({"/blog/steel"})
    public String steel() {
        return THEME_PREFIX + "cweb" + "/steel";
    }

    @GetMapping({"/blog/aluminumsmelting"})
    public String aluminumSmelting() {
        return THEME_PREFIX + "cweb" + "/aluminum_smelting";
    }

    @GetMapping({"/blog/spin"})
    public String spin() {
        return THEME_PREFIX + "cweb" + "/spin";
    }

    @GetMapping({"/blog/aviation"})
    public String aviation() {
        return THEME_PREFIX + "cweb" + "/aviation";
    }

    @GetMapping({"/blog/cement"})
    public String cement() {
        return THEME_PREFIX + "cweb" + "/cement";
    }

    @GetMapping({"/blog/plateglass"})
    public String plateglass() {
        return THEME_PREFIX + "cweb" + "/plateglass";
    }

    @GetMapping({"/blog/ceramics"})
    public String ceramics() {
        return THEME_PREFIX + "cweb" + "/ceramics";
    }

    @GetMapping({"/blog/coal"})
    public String coal() {
        return THEME_PREFIX + "cweb" + "/coal";
    }

    @GetMapping({"/blog/chemicalindustry"})
    public String chemicalindustry() {
        return THEME_PREFIX + "cweb" + "/chemicalindustry";
    }
}
